package com.github.xzb617.rpc;

import com.github.xzb617.rpc.core.RequestCaller;
import com.github.xzb617.rpc.entity.Server;
import com.github.xzb617.rpc.loadbalancer.LoadBalancer;
import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Map;

/**
 * 实现了负载均衡的请求
 */
public class LoadBalanceCaller {

    private final List<Server> servers;
    private final RequestCaller requestCaller;
    private final LoadBalancer loadBalancer;

    public LoadBalanceCaller(List<Server> servers, RequestCaller requestCaller, LoadBalancer loadBalancer) {
        this.servers = servers;
        this.requestCaller = requestCaller;
        this.loadBalancer = loadBalancer;
    }

    public <T> ResponseEntity<T> lbGet(String methodPath, Map<String, String> parameters, Map<String, String> headers, Class<T> responseType) {
        Server server = this.loadBalancer.choose(this.servers);
        return this.requestCaller.get(server, methodPath, parameters, headers, responseType);
    }

    public <T> ResponseEntity<T> lbPost(String methodPath, Map<String, String> parameters, Map<String, String> headers, Class<T> responseType) {
        Server server = this.loadBalancer.choose(this.servers);
        return this.requestCaller.post(server, methodPath, parameters, headers, responseType);
    }

    public <T> ResponseEntity<T> lbPut(String methodPath, Map<String, String> parameters, Map<String, String> headers, Class<T> responseType) {
        Server server = this.loadBalancer.choose(this.servers);
        return this.requestCaller.put(server, methodPath, parameters, headers, responseType);
    }

    public <T> ResponseEntity<T> lbDelete(String methodPath, Map<String, String> parameters, Map<String, String> headers, Class<T> responseType) {
        Server server = this.loadBalancer.choose(this.servers);
        return this.requestCaller.delete(server, methodPath, parameters, headers, responseType);
    }
}
